import Vue from 'vue'
import VueRouter from 'vue-router'
import {routerWideTraversal} from '@u/index.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      requireAuth: false // 是否需要登录验证
    }
  },
  {
    path: '/index',
    name: 'Indx',
    component: () => import('@/views/index.vue'),
    meta: {
      requireAuth: true // 是否需要登录验证
    },
    children: [{
      path: '/user',
      name: 'User',
      component: () => import('@/views/user/index.vue'),
      meta: {
        requireAuth: true
      }
    },{
      path: '/change',
      name: 'Change',
      component: () => import('@/views/change/index.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/putOnRecords',
      name: 'PutOnRecords',
      component: () => import('@/views/putOnRecords/index.vue'),
      meta: {
        requireAuth: true
      }
    },]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
    meta: {
      requireAuth: false
    }
  }, 
]

const router = new VueRouter({
  mode: 'history',  //去掉url中的#
  routes
})


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}


router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title;

  // window.scrollTo(0, 0);
  // 登录拦截
  if (to.meta.requireAuth) { // 判断跳转的路由是否需要登录
    if (Vue.prototype.$cookies.get("token")) { // 判断token是否存在

      next() // 已登录
    } else {
      // 未登录
      next({
        path: '/login',
        query: {
          source: to.fullPath
        }
      }
      )
    }

  }
  else {
    // 无需登录直接放行
    next()
  }
});

export default router
